package com.xce.gateway.predicate;

import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * @ClassName VipRoutePredicateFactory
 * @Description TODO
 * @Author lld
 * @Date 2025/7/7 21:26
 * @Version 1.0
 */
@Component
public class VipRoutePredicateFactory extends AbstractRoutePredicateFactory<VipRoutePredicateFactory.Config> {

    private static final String PARAM = "param";
    private static final String VALUE = "value";

    public VipRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(PARAM, VALUE);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new GatewayPredicate() {
            public boolean test(ServerWebExchange exchange) {
                String name = exchange.getRequest().getQueryParams().getFirst(config.param);

                return StringUtils.hasText(name) && name.equals(config.value);
            }
        };
    }
    @Validated
    @Data
    @NoArgsConstructor
    public static class Config {
        private @NotEmpty String param;

        private @NotEmpty String value;
    }
}
